'use strict';

module.exports = options => {
  return async function jwt(ctx, next) {
    const token = ctx.request.header.authorization;
    const whiteList = [
      '/token',
      '/admin/login',
      '/admin/dict_arr',
      'miniapp/help_center',
      '/miniapp/cover_shift',
      '/miniapp/job_opening_user',
      '/miniapp/dicts',
      '/miniapp/notices',
      '/miniapp/getAccessToken',
      '/miniapp/position/search',
      '/miniapp/getWeiXinPhone',
      '/miniapp/login/weapp',
      '/miniapp/ads',
      '/miniapp/getArticleByType',
      '/miniapp/user/shift_work',
      '/miniapp/lat',
      '/miniapp/user/employer_verify',
      '/miniapp/user/job_opening',
      '/admin/getUserInfo',
      '/miniapp/announcements',
      '/miniapp/upload',
      '/admin/upload',
      '/miniapp/position',
      '/miniapp/sms/code',
      '/miniapp/login/phone',
      '/miniapp/permits',
      '/miniapp/login',
      '/miniapp/specifications'
    ];

    // 使用更精确的路径匹配
    const isWhitelisted = (url) => {
      console.log(url)
      return !!whiteList.find(path =>  url.includes(path));
    };
    console.log(isWhitelisted(ctx.request.url))
    if (isWhitelisted(ctx.request.url)) {
      return next();
    }
    if (!token) {
      // ctx.status = 401;
      ctx.throw(401, '未登录或token已过期');

    }

    try {
      // 验证token
      const decoded = ctx.app.jwt.verify(token.replace('Bearer ', ''), options.secret);
      // 获取用户信息
      const user = await ctx.model.User.findOne({
        where: {
          user_id: decoded.user_id,
          status: true, // 只查询启用状态的用户
        },
        attributes: {
          exclude: [ 'password' ], // 排除敏感信息
        },
      });

      if (!user) {
        ctx.throw(401, '用户不存在或已被禁用');
      }

      // 如果是管理员账号，确保不能被禁用
      if (user.user_type==='admin' && !user.status) {
        await user.update({ status: true });
        ctx.app.logger.info(`管理员账号 ${user.username} 被自动重新启用`);
      }
      await next();
    } catch (err) {
      if (err.name === 'TokenExpiredError') {
        ctx.throw(401, 'token已过期');
      } else if (err.name === 'JsonWebTokenError') {
        ctx.throw(401, 'token无效');
      } else {
        throw err;
      }
    }
  };
};
